<template>
    <div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" @click="exportXlsx">导出Excel</el-button>
            </div>
            <el-table :data="tableData" border class="table" header-cell-class-name="table-header">
                <el-table-column prop="user_id" label="ID" width="150" align="center"></el-table-column>
                <el-table-column prop="user_nick_name" label="昵称"></el-table-column>
                <el-table-column prop="user_acc" label="账号"></el-table-column>
                <el-table-column prop="user_age" label="年龄"></el-table-column>
                <el-table-column prop="user_sex" label="性别"></el-table-column>
                <el-table-column prop="user_address" label="地址"></el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script setup lang="ts" name="export">
import { ref } from 'vue';
import * as XLSX from 'xlsx';
import { userListFunc } from '../api/index';

interface TableItem {
    user_id: number;
    user_nick_name: string;
    user_acc?: string;
    // user_pwd?: string;
    user_age?: string;
    user_sex?: string;
    user_address: string;
}

const tableData = ref<TableItem[]>([]);
// 获取表格数据
const getData = async () => {
    // 调用后台接口获取用户数据
    await userListFunc({page:1, pageSize: 100})
    .then(
        (res: any)=>{
            if(res.code == 200) {
                let arr = res.result.map((item: any)=>{
                    item.user_id = item.user_id.slice(0,4) +"***"+ item.user_id.slice(-4);
                    return item;
                })
                tableData.value = arr;
            }
            console.log(res.msg);
        }
    )
};
getData();

const list = [['序号', '昵称', '账号', '年龄', '性别', '地址']];
const exportXlsx = () => {
    tableData.value.map((item: any, i: number) => {
        const arr: any[] = [i + 1];
        arr.push(...[item.user_id, item.user_nick_name, item.user_acc, item.user_age, item.user_sex,item.user_address]);
        list.push(arr);
    });
    let WorkSheet = XLSX.utils.aoa_to_sheet(list);
    let new_workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(new_workbook, WorkSheet, '第一页');
    XLSX.writeFile(new_workbook, `表格.xlsx`);
};

</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #f56c6c;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
